package frame;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore;
import android.support.annotation.ColorRes;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.menhoo.menhoolibrary.R;
import com.example.menhoo.toollibrary.common.assist.Check;
import com.example.menhoo.toollibrary.common.assist.IMEHelper;
import com.example.menhoo.toollibrary.common.assist.Network;
import com.example.menhoo.toollibrary.common.helper.MessageUtil;
import com.example.menhoo.toollibrary.common.utils.NumberUtil;
import com.example.menhoo.toollibrary.common.utils.UriUtil;
import com.gyf.barlibrary.ImmersionBar;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.LogUtils;
import com.lsjwzh.loadingeverywhere.GenericStatusLayout;
import com.pizidea.imagepicker.AndroidImagePicker;
import com.pizidea.imagepicker.bean.ImageItem;
import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;
import com.rey.material.app.ThemeManager;
import com.rey.material.widget.ProgressView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import application.UIApplication;
import interfaces.IDownLoadListener;
import interfaces.IFileChooserListener;
import interfaces.IReturnObject;
import interfaces.IUpLoadListener;
import receiver.AndroidNetConnectionChangeStateReceiver;
import receiver.DownloadCancelledReceiver;
import receiver.DownloadErrorReceiver;
import receiver.DownloadFinishReceiver;
import receiver.DownloadLoadingReceiver;
import receiver.DownloadStartReceiver;
import receiver.FileChooserReceiver;
import receiver.NetStateReceiver;
import receiver.UploadCancelledReceiver;
import receiver.UploadErrorReceiver;
import receiver.UploadFinishReceiver;
import receiver.UploadLoadingReceiver;
import receiver.UploadStartReceiver;
import service.DownLoadService;
import service.UDPPushService;


public class UIActivity extends AppCompatActivity {
    private long loadingHideTime = 700;
    /**
     * http请求之后多长时间超时
     */
    private int Http_Timeout = UIApplication.NetWorkTimeOut;
    /**
     * http请求缓存,多长时间返回相同结果
     */
    private long Http_CacheTime = 5000;

    private long promptShotShowTime = 1000;
    private long promptLongShowTime = 2000;

    private Handler handler = new Handler();
    private HttpUtils http = new HttpUtils(Http_Timeout);
    private List<HttpHandler> httpHandlerList = new ArrayList();
    //private DbUtils db;
    private BitmapUtils bitmapLoader;
    private BitmapUtils iconLoader;
    private GenericStatusLayout genericStatusLayout;
    private GenericStatusLayout.ILayerCreator layerCreator;
    //UDP推送服务
    private Intent udpPushService;

    //下载上传服务
    private DownLoadService downLoadService;
    private ServiceConnection downLoadServiceConn;
    private DownloadStartReceiver downloadStartReceiver;
    private DownloadLoadingReceiver downloadLoadingReceiver;
    private DownloadFinishReceiver downloadFinishReceiver;
    private DownloadErrorReceiver downloadErrorReceiver;
    private DownloadCancelledReceiver downloadCancelledReceiver;

    private UploadStartReceiver uploadStartReceiver;
    private UploadLoadingReceiver uploadLoadingReceiver;
    private UploadFinishReceiver uploadFinishReceiver;
    private UploadErrorReceiver uploadErrorReceiver;
    private UploadCancelledReceiver uploadCancelledReceiver;

    private IDownLoadListener iDownLoadListener;
    private IUpLoadListener iUpLoadListener;
    //选择文件
    public static final int File_Chooser = 0xab99;
    private String mCameraFilePath;
    private FileChooserReceiver fileChooserReceiver;
    private IFileChooserListener iFileChooserListener;

    //网络监听Receiver
    private AndroidNetConnectionChangeStateReceiver androidNetConnectionChangeStateReceiver = null;
    private NetStateReceiver netStateReceiver = null;
    //ui
    private LinearLayout frame_ui_context;
    private LinearLayout frame_ui_hint;
    private FrameLayout frame_ui_title_status_prompt_info;
    private View frame_ui_title;
    private LinearLayout frame_ui_layout_custom_cnx;
    private ImageView frame_ui_btn_back;
    private TextView frame_ui_tv_title_text;

    private View loadingView;
    private View emptyView;
    private View errorView;

    private int loadingViewResID = R.layout.frame_ui_loading;
    private int emptyViewResID = R.layout.frame_ui_empty;
    private int errorViewResID = R.layout.frame_ui_error;
    /**
     * 错误页面,点击重试时候的回调函数
     */
    private IReturnObject<String> errorViewCall = null;

    public void setLoadingView(int resID) {
        loadingViewResID = resID;
    }

    public View getLoadingView() {
        return loadingView;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        beforeOnCreate();
        super.onCreate(savedInstanceState);
        afterOnCreate();
        //初始化状态栏
        initStatusBar();
        http.configCurrentHttpCacheExpiry(Http_CacheTime);
        http.configDefaultHttpCacheExpiry(Http_CacheTime);
        //布局
        super.setContentView(R.layout.frame_ui);


        //实例化
        frame_ui_context = (LinearLayout) findViewById(R.id.frame_ui_context);
        frame_ui_hint = (LinearLayout) findViewById(R.id.frame_ui_hint);
        frame_ui_title_status_prompt_info = (FrameLayout) findViewById(R.id.frame_ui_title_status_prompt_info);
        frame_ui_title = findViewById(R.id.frame_ui_title);
        frame_ui_layout_custom_cnx = (LinearLayout) findViewById(R.id.frame_ui_layout_custom_cnx);
        frame_ui_btn_back =  findViewById(R.id.frame_ui_btn_back);
        frame_ui_tv_title_text = (TextView) findViewById(R.id.frame_ui_tv_title_text);
        //onclick
        frame_ui_btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
                IMEHelper.hideIME(UIActivity.this,true);

            }
        });
        //初始化一些参数
        ViewUtils.inject(this);
        //db = DbUtils.create(this);
        bitmapLoader = initBitmapUtils(UIApplication.getAppCachePath(this));
        iconLoader = initBitmapUtils(UIApplication.getAppIconCachePath(this));
        initGenericStatusLayout();
        //标题
        setTitle(getTitle());

        //绑定"下载服务"
        if (UIApplication.getRunDownloadService()) {
            bindDownLoadService();
        }
        //实例化网络状态监听
        if (UIApplication.isNetworkStateReceiver()) {
            androidNetConnectionChangeStateReceiver = new AndroidNetConnectionChangeStateReceiver();
            netStateReceiver = new NetStateReceiver() {
                @Override
                public void run(Context context, Intent intent, boolean isWifi, boolean isNetworkAvailable, String message) {
                    onNetworkStateChange(context, intent, isWifi, isNetworkAvailable, message);
                }
            };
        }
        //绑定文件选择器receiver
        bindFileChooser();
    }

    private void initStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.setStatusBarColor(getResources().getColor(android.R.color.transparent));
        }
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f) //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                .init();
    }

    protected void setStatusBarVisible(int visible) {
        findViewById(R.id.status).setVisibility(visible);
    }

    protected void setStatusBarBg(@ColorRes int color) {
        findViewById(R.id.status).setBackgroundResource(color);
    }

    /**
     * 连接服务器进行接受推送消息
     *
     * @param deviceID
     * @param appid    1-255
     * @param ip
     * @param port     默认9999
     */
    public void startUDPPushService(String deviceID, int appid, String ip, String port) {
        SharedPreferences udpAccount = this.getSharedPreferences(UDPPushService.DEFAULT_PRE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = udpAccount.edit();
        editor.putString(UDPPushService.SERVER_IP, ip);
        if (Check.isEmpty(port)) {
            port = "9966";
        }
        editor.putString(UDPPushService.SERVER_PORT, port);
        editor.putString(UDPPushService.DEVICE_ID, deviceID);
        editor.putInt(UDPPushService.APP_ID, appid);
        editor.commit();

        udpPushService = new Intent(this, UDPPushService.class);
        udpPushService.putExtra("CMD", "RESET");
        this.startService(udpPushService);

    }

    /**
     * 停止UDP推送服务
     */
    public void stopUDPPushService() {
        if (udpPushService != null) {
            SharedPreferences udpAccount = this.getSharedPreferences(UDPPushService.DEFAULT_PRE_NAME, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = udpAccount.edit();
            editor.putString(UDPPushService.SERVER_IP, "");
            editor.putString(UDPPushService.SERVER_PORT, "");
            editor.putString(UDPPushService.DEVICE_ID, "");
            editor.putInt(UDPPushService.APP_ID, 1);
            editor.commit();
            this.stopService(udpPushService);
        }
    }

    /**
     * 初始化图片载入器
     *
     * @param cachePath 缓存文件的物理位置
     * @return
     */
    private BitmapUtils initBitmapUtils(String cachePath) {
        BitmapUtils bitmapUtils = new BitmapUtils(this, cachePath);
        return bitmapUtils;
    }

    /**
     * 得到一个 HttpUtils 对象
     *
     * @return
     */
    public HttpUtils getHttp() {
        return http;
    }

    Map<String, View> promptInfoMap = new HashMap();

    /**
     * 状态栏, 提示信息
     *
     * @param message   提示信息
     * @param textColor 文字颜色
     * @param backColor 背景颜色
     * @param showType  显示的方式,0短暂的提示,1稍微长一些时间的提示,2一直提示直到调用promptInfoHide()
     * @return 返回一个 String 类型的标识 ,用于promptInfoHide(String) 参数 ,如果返回的是null则没有任何意义说明失败
     */
    public String promptInfoShow(String message, int textColor, int backColor, int showType) {
        return promptInfoShow(0, message, textColor, backColor, showType);
    }

    /**
     * 状态栏, 提示信息
     *
     * @param imageRid  图片资源id
     * @param message   提示信息
     * @param textColor 文字颜色
     * @param backColor 背景颜色
     * @param showType  显示的方式,0短暂的提示,1稍微长一些时间的提示,2一直提示直到调用promptInfoHide()
     * @return 返回一个 String 类型的标识 ,用于promptInfoHide(String) 参数 ,如果返回的是null则没有任何意义说明失败
     */
    public String promptInfoShow(int imageRid, String message, int textColor, int backColor, int showType) {
        final String key = NumberUtil.getGuid();
        statusBarDisplay(false);
        try {
            View view = getLayoutInflater().inflate(R.layout.frame_ui_status_bar_prompt_info, null);
            LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.frame_ui_status_bar_prompt_info_background);
            ImageView image = (ImageView) view.findViewById(R.id.frame_ui_status_bar_prompt_info_image);
            TextView text = (TextView) view.findViewById(R.id.frame_ui_status_bar_prompt_info_text);

            linearLayout.setBackgroundColor(backColor);

            text.setTextColor(textColor);
            text.setText(message);

            if (imageRid > 0) {
                int statusBarHeight = getStatusBarHeight(this.getBaseContext());
                int statusBarHeight_5_1 = statusBarHeight / 5;
                ViewGroup.LayoutParams layoutParams = image.getLayoutParams();
                layoutParams.height = statusBarHeight - statusBarHeight_5_1;
                layoutParams.width = statusBarHeight - statusBarHeight_5_1;
                image.setLayoutParams(layoutParams);

                image.setImageResource(imageRid);
            } else {
                image.setVisibility(View.GONE);
            }

            frame_ui_title_status_prompt_info.addView(view);
            view.startAnimation(UIApplication.getAnimationSet());

            promptInfoMap.put(key, view);

            switch (showType) {
                case 0:
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            promptInfoHide(key);
                        }
                    }, promptShotShowTime);
                    break;
                case 1:
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            promptInfoHide(key);
                        }
                    }, promptLongShowTime);
                    break;
                case 2:
                    break;
            }

            return key;

        } catch (Exception e) {
            promptInfoHide(key);
            LogUtils.e(e.getMessage() + "");
        }

        return null;
    }

    /**
     * 清除 状态栏, 提示信息
     *
     * @param promptID promptInfoShow 方法的返回值
     */
    public void promptInfoHide(String promptID) {
        if (promptInfoMap.containsKey(promptID)) {
            View view = promptInfoMap.get(promptID);
            if (view != null) {
                frame_ui_title_status_prompt_info.removeView(view);
            }
        }

        if (frame_ui_title_status_prompt_info.getChildCount() == 0) {
            statusBarDisplay(true);
        }
    }

    /**
     * 清除所有 状态栏, 提示信息
     */
    public void promptInfoHideAll() {
        frame_ui_title_status_prompt_info.removeAllViews();
        statusBarDisplay(true);
    }

    /**
     * 显示/隐藏 状态栏
     *
     * @param isShow true显示
     */
    public void statusBarDisplay(boolean isShow) {
        if (!isShow) {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(lp);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        } else {
            WindowManager.LayoutParams attr = getWindow().getAttributes();
            attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attr);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }
    }

    /**
     * 设置沉侵式状态栏,并设置默认颜色
     *
     * @param color
     */
    public void setImmerseStatusBar(int color) {
        //frame_ui_title_status_prompt_info.setBackgroundColor(color);
        //setImmerseLayout(frame_ui_title_status_prompt_info);
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = getWindow();
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(color);

                //底部导航栏
                //window.setNavigationBarColor(activity.getResources().getColor(colorResId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置沉侵式状态栏,并设置默认android当前系统的半透明样式
     * bug 再弹出键盘的时候 页面不能正常缩放以适应键盘，官方的解释是无法计算statusbar的高度
     */
    public void setImmerseLayout(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
                /*window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);*/
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

            int statusBarHeight = getStatusBarHeight(this.getBaseContext());
            ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
            layoutParams.height = statusBarHeight;
            view.setLayoutParams(layoutParams);
//            view.setPadding(0, statusBarHeight, 0, 0);
        }
    }

    /**
     * 用于获取状态栏的高度。 使用Resource对象获取（推荐这种方式）
     *
     * @return 返回状态栏高度的像素值。
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen",
                "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 在onCreate之前执行 主要用来设置全屏
     */
    public void beforeOnCreate() {
    }

    /**
     * 在onCreate之后执行 主要用来设置全屏
     */
    public void afterOnCreate() {
    }

    /**
     * 显示内容(除了title) 淡出
     */
    public void showContent() {
        frame_ui_context.setVisibility(View.VISIBLE);

        frame_ui_context.startAnimation(UIApplication.getAnimationSet());

    }

    /**
     * 提示内容 淡出
     */
    public void showHint() {
        frame_ui_hint.setVisibility(View.VISIBLE);

        frame_ui_hint.startAnimation(UIApplication.getAnimationSet());

    }

    /**
     * 隐藏内容(除了title)
     */
    public void hideContent() {
        frame_ui_context.setVisibility(View.GONE);
    }

    /**
     * 隐藏提示
     */
    public void hideHint() {
        frame_ui_hint.setVisibility(View.GONE);
    }

    /**
     * 返回异步图片载入器(普通图片)缓存周期短,默认一天
     *
     * @return
     */
    public BitmapUtils getBitmapLoader() {
        return bitmapLoader;
    }

    /**
     * 返回异步图片载入器(ICON)缓存周期很长,默认一年
     *
     * @return
     */
    public BitmapUtils getIconLoader() {
        return iconLoader;
    }

    /**
     * 隐藏软键盘
     */
    public void hideIME() {

        IMEHelper.hideIME(this, true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        /*我们应该在销毁activity的时候也移除和销毁当中我们实例化的一些资源*/
        //移除所有遮罩层
        hideAll();
        //隐藏软键盘
        hideIME();

        //解除绑定如果有绑定的话
        unBindDownLoadService();
        unBindFileChooser();

        //销毁正在请求的网络资源
        //取消所有的url请求
        for (HttpHandler httpHandler : httpHandlerList) {
            if (httpHandler != null) {
                httpHandler.cancel();
            }
        }
        httpHandlerList.removeAll(httpHandlerList);
        httpHandlerList = null;
    }

    /**
     * 初始化遮罩层
     */
    public void initGenericStatusLayout() {
        genericStatusLayout = new GenericStatusLayout(this);
        layerCreator = new GenericStatusLayout.ILayerCreator() {
            @Override
            public View createLoadingLayer() {
                loadingView = getLayoutInflater().inflate(loadingViewResID, null);
                loadingView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        return;
                    }
                });
                return loadingView;
            }

            @Override
            public View createEmptyLayer() {
                emptyView = getLayoutInflater().inflate(emptyViewResID, null);
                return emptyView;
            }

            @Override
            public View createErrorLayer() {
                errorView = getLayoutInflater().inflate(errorViewResID, null);
                if (errorViewCall != null) {
                    errorView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            errorViewCall.returnResult("");
                        }
                    });
                }

                return errorView;
            }
        };
        genericStatusLayout.setLayerCreator(layerCreator);
        genericStatusLayout.attachTo(frame_ui_context);
    }

    /**
     * 得到数据库操作对象
     *
     * @return
     */
    public DbUtils getDB() {
        //return db;
        return UIApplication.getDB();
    }

    @Override
    public void setContentView(int layoutResID) {
        try {
            View.inflate(this, layoutResID, frame_ui_context);
        } catch (Exception e) {
            super.setContentView(layoutResID);
        }
    }

    /*
    设置提示试图
     */
    public void setHintView(int layoutResID) {
        try {
            View.inflate(this, layoutResID, frame_ui_hint);
        } catch (Exception e) {
        }
    }

    @Override
    public void onBackPressed() {
        try {
            super.onBackPressed();
        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
        }

    }

    /**
     * 注入标题导航栏右侧的自定义布局
     *
     * @param layoutResID
     */
    public void setCustomRightButton(int layoutResID) {
        try {
            View.inflate(this, layoutResID, frame_ui_layout_custom_cnx);
        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
        }
    }

    /**
     * 是否显示标题导航栏,默认显示
     *
     * @param isShow true显示  false隐藏
     */
    public void setTitleDisplay(boolean isShow) {
        if (isShow) {
            frame_ui_title.setVisibility(View.VISIBLE);
        } else {
            frame_ui_title.setVisibility(View.GONE);
        }

    }

    /**
     * 是否显示返回按钮
     *
     * @param isShow
     */
    public void setBtnBackDisplay(boolean isShow) {
        if (isShow) {
            frame_ui_btn_back.setVisibility(View.VISIBLE);
        } else {
            frame_ui_btn_back.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        frame_ui_tv_title_text.setText(title);
    }

    @Override
    public void setTitle(int titleId) {
        frame_ui_tv_title_text.setText(getString(titleId));
    }

    public void showLoading() {
        hideAll();
        genericStatusLayout.showLoading();
        if (loadingView != null) {
            ProgressView pv_linear_colors = (ProgressView) loadingView.findViewById(R.id.progress_pv_linear_colors);
            pv_linear_colors.start();
        }
    }

    public void hideLoading() {
        if (loadingView != null) {
            ProgressView pv_linear_colors = (ProgressView) loadingView.findViewById(R.id.progress_pv_linear_colors);
            pv_linear_colors.stop();
        }
        genericStatusLayout.hideLoading();
    }

    public void showEmpty() {
        hideAll();
        genericStatusLayout.showEmpty();
    }

    public void hideEmpty() {
        genericStatusLayout.hideEmpty();
    }

    public void showError(IReturnObject<String> iReturnObject) {
        hideAll();
        errorViewCall = iReturnObject;
        genericStatusLayout.showError();
    }

    public void hideError() {
        genericStatusLayout.hideError();
    }

    /**
     * 延迟隐藏所有的遮罩层 loading empty error
     *
     * @param delayMillis 延迟隐藏 时间
     */
    public void hideAll(long delayMillis) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                hideAll();
            }
        }, delayMillis);
    }

    /**
     * 隐藏所有的遮罩层 loading empty error
     */
    public void hideAll() {
        hideError();
        hideEmpty();
        hideLoading();
        //隐藏软键盘
        IMEHelper.hideIME(this, true);
    }

    private void httpHelp(final HttpMethod GetOrPost, final String url, final RequestParams params, final IReturnObject<String> returnObj) {
        httpHelp(GetOrPost, url, params, new RequestCallBack<String>() {
            @Override
            public void onStart() {

            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {

            }

            @Override
            public void onCancelled() {
                LogUtils.d("url:" + url + ":请求已经取消");
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                LogUtils.d(responseInfo.result + "");
                if (returnObj != null)
                    returnObj.returnResult(responseInfo.result);
                hideAll(loadingHideTime);
            }

            @Override
            public void onFailure(HttpException e, String s) {
                showError(new IReturnObject<String>() {
                    @Override
                    public void returnResult(String result) {
                        httpHelp(GetOrPost, url, params, returnObj);
                    }
                });
                if (returnObj != null)
                    returnObj.returnResult(null);

                LogUtils.e(s + "");
            }
        });
    }

    /**
     * http请求
     *
     * @param GetOrPost get请求 还是 post请求
     * @param url       url地址
     * @param params    要传递的url参数(键值对)
     * @param callBack  当中有 start loading success 和 failure相关回调函数
     */
    public void httpHelp(HttpMethod GetOrPost, String url, RequestParams params, RequestCallBack callBack) {
        httpHelp(GetOrPost, url, params, callBack, true);
    }

    /**
     * http请求
     *
     * @param GetOrPost get请求 还是 post请求
     * @param url       url地址
     * @param params    要传递的url参数(键值对)
     * @param callBack  当中有 start loading success 和 failure相关回调函数
     */
    public void httpHelp(HttpMethod GetOrPost, String url, RequestParams params, RequestCallBack callBack, boolean isShowLoading) {
        if (isShowLoading) {
            showLoading();
        }
        HttpSend(GetOrPost, url, params, callBack);
    }

    /**
     * http请求(最后一级)
     *
     * @param GetOrPost get请求 还是 post请求
     * @param url       url地址
     * @param params    要传递的url参数(键值对)
     * @param callBack  当中有 start loading success 和 failure相关回调函数
     */
    public void HttpSend(final HttpMethod GetOrPost, final String url, final RequestParams params, final RequestCallBack callBack) {
        //检查一下网络状态
        Network.isNetworkAvailable(this, url, new com.example.menhoo.toollibrary.android.async.IReturnObject<Boolean>() {
            @Override
            public void returnResult(Boolean isNetwork) {
                if (isNetwork) {
                    Intent it = new Intent();// 创建Intent对象
                    it.setAction(NetStateReceiver.Action);
                    it.putExtra("isNetworkAvailable", true);
                    it.putExtra("message", getString(R.string.available_network_title));
                    sendBroadcast(it);

                    HttpHandler handle = http.send(GetOrPost, url, params, callBack);
                    if (httpHandlerList == null) {
                        httpHandlerList = new ArrayList();
                    }
                    httpHandlerList.add(handle);
                } else {
                    String message = getString(R.string.no_conn_server);

                    Intent it = new Intent();// 创建Intent对象
                    it.setAction(NetStateReceiver.Action);
                    it.putExtra("isNetworkAvailable", false);
                    it.putExtra("message", message);
                    sendBroadcast(it);

                    //MessageUtil.showShortToast(UIActivity.this, "无网络");
                    callBack.onFailure(new HttpException(message), message);
                    //hideAll(loadingHideTime);
                }
            }
        });

    }

    /**
     * http请求
     *
     * @param GetOrPost get请求 还是 post请求
     * @param url       url地址
     * @param callBack  当中有 start loading success 和 failure相关回调函数
     */
    public void httpHelp(HttpMethod GetOrPost, String url, RequestCallBack callBack) {
        httpHelp(GetOrPost, url, null, callBack);
    }

    /**
     * 可以传递参数的Get Http请求
     *
     * @param url       url地址
     * @param params    要传递的url参数(键值对)
     * @param returnObj 成功之后返回的结果字符串
     */
    public void httpGet(String url, RequestParams params, IReturnObject<String> returnObj) {
        httpHelp(HttpMethod.GET, url, params, returnObj);
    }

    /**
     * Get Http请求
     *
     * @param url       url地址
     * @param returnObj 成功之后返回的结果字符串
     */
    public void httpGet(String url, IReturnObject<String> returnObj) {
        httpGet(url, null, returnObj);
    }

    /**
     * 可以传递参数的Post Http请求
     *
     * @param url       url地址
     * @param params    要传递的url参数(键值对)
     * @param returnObj 成功之后返回的结果字符串
     */
    public void httpPost(String url, RequestParams params, IReturnObject<String> returnObj) {
        httpHelp(HttpMethod.POST, url, params, returnObj);
    }

    /**
     * Post Http请求
     *
     * @param url       url地址
     * @param returnObj 成功之后返回的结果字符串
     */
    public void httpPost(String url, IReturnObject<String> returnObj) {
        httpPost(url, null, returnObj);
    }

    /**
     * 横 竖 屏 切换
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            LogUtils.d("当前屏幕为横屏");
        } else {
            LogUtils.d("当前屏幕为竖屏");
        }
    }

    /**
     * 绑定下载/上传服务 在此AndroidManifest.xml 中一定要注册 service 否则无效(已经在此library注册了)
     */
    private void bindDownLoadService() {
        downLoadServiceConn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                try {
                    downLoadService = ((DownLoadService.DownLoadBinder) service).getService();
                } catch (Exception e) {
                    LogUtils.e(e.getMessage() + "");
                }

            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                downLoadService = null;
            }
        };
        if (downLoadServiceConn != null) {
            Intent it_service = new Intent(getApplicationContext(), DownLoadService.class);
            bindService(it_service, downLoadServiceConn, Context.BIND_AUTO_CREATE);
        }

        //初始化接收器
        downloadStartReceiver = new DownloadStartReceiver() {
            @Override
            public void DownloadStart(Context context, Intent intent, String url, String tag) {
                if (iDownLoadListener != null) {
                    iDownLoadListener.DownloadStart(context, intent, url, tag);
                }
            }
        };
        downloadLoadingReceiver = new DownloadLoadingReceiver() {
            @Override
            public void DownloadLoading(Context context, Intent intent, String url, long total, long current, String tag) {
                if (iDownLoadListener != null) {
                    iDownLoadListener.DownloadLoading(context, intent, url, total, current, tag);
                }
            }
        };
        downloadFinishReceiver = new DownloadFinishReceiver() {
            @Override
            public void DownloadFinish(Context context, Intent intent, String url, String filePath, String tag) {
                if (iDownLoadListener != null) {
                    iDownLoadListener.DownloadFinish(context, intent, url, filePath, tag);
                }
            }

        };
        downloadErrorReceiver = new DownloadErrorReceiver() {
            @Override
            public void DownloadError(Context context, Intent intent, String url, String errorMsg, String tag) {
                if (iDownLoadListener != null) {
                    iDownLoadListener.DownloadError(context, intent, url, errorMsg, tag);
                }
            }
        };
        downloadCancelledReceiver = new DownloadCancelledReceiver() {
            @Override
            public void DownloadCancelled(Context context, Intent intent, String url, String tag) {
                if (iDownLoadListener != null) {
                    iDownLoadListener.DownloadCancelled(context, intent, url, tag);
                }
            }
        };
        uploadStartReceiver = new UploadStartReceiver() {
            @Override
            public void UploadStart(Context context, Intent intent, String url, String tag) {
                if (iUpLoadListener != null) {
                    iUpLoadListener.UploadStart(context, intent, url, tag);
                }
            }
        };
        uploadLoadingReceiver = new UploadLoadingReceiver() {
            @Override
            public void UploadLoading(Context context, Intent intent, String url, long total, long current, String tag) {
                if (iUpLoadListener != null) {
                    iUpLoadListener.UploadLoading(context, intent, url, total, current, tag);
                }
            }
        };
        uploadFinishReceiver = new UploadFinishReceiver() {
            @Override
            public void UploadFinish(Context context, Intent intent, String url, String filePath, String webResult, String tag) {
                if (iUpLoadListener != null) {
                    iUpLoadListener.UploadFinish(context, intent, url, filePath, webResult, tag);
                }
            }
        };
        uploadErrorReceiver = new UploadErrorReceiver() {
            @Override
            public void UploadError(Context context, Intent intent, String url, String errorMsg, String tag) {
                if (iUpLoadListener != null) {
                    iUpLoadListener.UploadError(context, intent, url, errorMsg, tag);
                }
            }
        };
        uploadCancelledReceiver = new UploadCancelledReceiver() {
            @Override
            public void UploadCancelled(Context context, Intent intent, String url, String tag) {
                if (iUpLoadListener != null) {
                    iUpLoadListener.UploadCancelled(context, intent, url, tag);
                }
            }
        };

        //注册download
        registerReceiver(downloadStartReceiver, new IntentFilter(downloadStartReceiver.Action));
        registerReceiver(downloadLoadingReceiver, new IntentFilter(downloadLoadingReceiver.Action));
        registerReceiver(downloadFinishReceiver, new IntentFilter(downloadFinishReceiver.Action));
        registerReceiver(downloadErrorReceiver, new IntentFilter(downloadErrorReceiver.Action));
        registerReceiver(downloadCancelledReceiver, new IntentFilter(downloadCancelledReceiver.Action));
        //注册upload
        registerReceiver(uploadStartReceiver, new IntentFilter(uploadStartReceiver.Action));
        registerReceiver(uploadLoadingReceiver, new IntentFilter(uploadLoadingReceiver.Action));
        registerReceiver(uploadFinishReceiver, new IntentFilter(uploadFinishReceiver.Action));
        registerReceiver(uploadErrorReceiver, new IntentFilter(uploadErrorReceiver.Action));
        registerReceiver(uploadCancelledReceiver, new IntentFilter(uploadCancelledReceiver.Action));
    }

    /**
     * 解除下载/上传服务的绑定
     */
    private void unBindDownLoadService() {
        if (downLoadServiceConn != null) {
            unbindService(downLoadServiceConn);
        }
        //解除download
        if (downloadStartReceiver != null) {
            unregisterReceiver(downloadStartReceiver);
        }
        if (downloadLoadingReceiver != null) {
            unregisterReceiver(downloadLoadingReceiver);
        }
        if (downloadFinishReceiver != null) {
            unregisterReceiver(downloadFinishReceiver);
        }
        if (downloadErrorReceiver != null) {
            unregisterReceiver(downloadErrorReceiver);
        }
        if (downloadCancelledReceiver != null) {
            unregisterReceiver(downloadCancelledReceiver);
        }
        //解除upload
        if (uploadStartReceiver != null) {
            unregisterReceiver(uploadStartReceiver);
        }
        if (uploadLoadingReceiver != null) {
            unregisterReceiver(uploadLoadingReceiver);
        }
        if (uploadFinishReceiver != null) {
            unregisterReceiver(uploadFinishReceiver);
        }
        if (uploadErrorReceiver != null) {
            unregisterReceiver(uploadErrorReceiver);
        }
        if (uploadCancelledReceiver != null) {
            unregisterReceiver(uploadCancelledReceiver);
        }
    }

    /**
     * 设置下载监控
     *
     * @param iDownLoadListener
     */
    public void setDownLoadReceiverHandle(IDownLoadListener iDownLoadListener) {
        this.iDownLoadListener = iDownLoadListener;
    }

    /**
     * 设置上传监控
     *
     * @param iUpLoadListener
     */
    public void setUploadLoadReceiverHandle(IUpLoadListener iUpLoadListener) {
        this.iUpLoadListener = iUpLoadListener;
    }

    /**
     * 得到下载/上传服务对象实例(有可能为空)
     *
     * @return
     */
    public DownLoadService getDownLoadService() {
        return downLoadService;
    }

    private Intent createDefaultOpenableIntent() {
        // Create and return a chooser with the default OPENABLE
        // actions including the camera, camcorder and sound
        // recorder where available.
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");

        Intent chooser = createChooserIntent(createCameraIntent(),
                createSoundRecorderIntent());
        chooser.putExtra(Intent.EXTRA_INTENT, i);
        return chooser;
    }

    private Intent createChooserIntent(Intent... intents) {
        Intent chooser = new Intent(Intent.ACTION_CHOOSER);
        chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
        chooser.putExtra(Intent.EXTRA_TITLE, "请选择");
        return chooser;
    }

    private Intent createCameraIntent() {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File externalDataDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DCIM);
        File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
                File.separator + "Camera");
        cameraDataDir.mkdirs();
        mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
                System.currentTimeMillis() + ".jpg";
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
        return cameraIntent;
    }

    private Intent createCamcorderIntent() {
        return new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    }

    private Intent createSoundRecorderIntent() {
        return new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
    }

    /**
     * 打开文件选择界面 单选
     *
     * @param iFileChooserListener 设置文件选择器选择到一个文件之后的监控
     */
    public void openFileChooser(IFileChooserListener iFileChooserListener) {
        try {
            this.iFileChooserListener = iFileChooserListener;
            startActivityForResult(createDefaultOpenableIntent(), File_Chooser);

        } catch (android.content.ActivityNotFoundException ex) {
            MessageUtil.showShortToast(this, "请安装文件管理器");
        }
    }

    /**
     * 打开图片选择界面 单选
     *
     * @param iFileChooserListener 设置文件选择器选择到一个文件之后的监控
     */
    public void openImageFileChooserSingle(boolean isShowCamera, IFileChooserListener iFileChooserListener) {
        try {
            this.iFileChooserListener = iFileChooserListener;
            AndroidImagePicker.getInstance().pickSingle(UIActivity.this, isShowCamera, new AndroidImagePicker
                    .OnImagePickCompleteListener() {
                @Override
                public void onImagePickComplete(List<ImageItem> items) {
                    if (items != null && items.size() > 0) {
                        //通知
                        Intent it = new Intent();// 创建Intent对象
                        it.setAction(FileChooserReceiver.Action);
                        String path = "";
                        for (ImageItem item : items) {
                            if (items.indexOf(item) != 0) {
                                path += ",";
                            }
                            path += item.path;
                        }

                        it.putExtra("fileFullName", path);
                        sendBroadcast(it);
                    }
                }
            });

        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
        }
    }

    /**
     * 打开图片选择界面 多选
     *
     * @param isShowCamera         显示拍照按钮
     * @param selectImageCount     可选图片个数
     * @param iFileChooserListener 设置文件选择器选择到一个文件之后的监控
     */
    public void openImageFileChooserMulti(boolean isShowCamera, int selectImageCount, IFileChooserListener iFileChooserListener) {
        try {
            this.iFileChooserListener = iFileChooserListener;
            AndroidImagePicker.getInstance().setSelectLimit(selectImageCount);
            AndroidImagePicker.getInstance().pickMulti(UIActivity.this, isShowCamera, new AndroidImagePicker
                    .OnImagePickCompleteListener() {
                @Override
                public void onImagePickComplete(List<ImageItem> items) {
                    if (items != null && items.size() > 0) {
                        //通知
                        Intent it = new Intent();// 创建Intent对象
                        it.setAction(FileChooserReceiver.Action);
                        String path = "";
                        for (ImageItem item : items) {
                            if (items.indexOf(item) != 0) {
                                path += ",";
                            }
                            path += item.path;
                        }

                        it.putExtra("fileFullName", path);
                        sendBroadcast(it);
                    }
                }
            });

        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
        }
    }

    /**
     * 打开图片选择并且按照范围裁剪图片
     *
     * @param isShowCamera                是否能拍照
     * @param cropSize                    大小一般都设置为 120
     * @param onImageCropCompleteListener 回调函数，里面会有裁剪之后的Bitmap
     */
    public void openImageFileChooserCrop(boolean isShowCamera, int cropSize, AndroidImagePicker.OnImageCropCompleteListener onImageCropCompleteListener) {
        AndroidImagePicker.getInstance().pickAndCrop(UIActivity.this, isShowCamera, cropSize, onImageCropCompleteListener);
    }

    /**
     * 绑定文件选择
     */
    private void bindFileChooser() {
        //初始化接收器
        fileChooserReceiver = new FileChooserReceiver() {
            @Override
            public void FileChooser(Context context, Intent intent, String fileFullName) {
                if (iFileChooserListener != null) {
                    iFileChooserListener.FileChooser(context, intent, fileFullName);

                    if (fileFullName != null && !fileFullName.equalsIgnoreCase("null")) {

                    } else {
                        LogUtils.e("FileChooser选择文件的时候得到了null值");
                    }

                }
            }
        };
        //注册fileChooserReceiver
        registerReceiver(fileChooserReceiver, new IntentFilter(fileChooserReceiver.Action));
    }

    /**
     * 文件选择解除绑定
     */
    private void unBindFileChooser() {
        if (fileChooserReceiver != null) {
            unregisterReceiver(fileChooserReceiver);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_CANCELED) {
            //通知
            Intent it = new Intent();// 创建Intent对象
            it.setAction(FileChooserReceiver.Action);
            String path = null;
            it.putExtra("fileFullName", path);
            sendBroadcast(it);
            return;
        }
        if (requestCode == File_Chooser) {
            Uri result = data == null || resultCode != Activity.RESULT_OK ? null : data.getData();

            // As we ask the camera to save the result of the user taking
            // a picture, the camera application does not return anything other
            // than RESULT_OK. So we need to check whether the file we expected
            // was written to disk in the in the case that we
            // did not get an intent returned but did get a RESULT_OK. If it was,
            // we assume that this result has came back from the camera.
            if (result == null && resultCode == Activity.RESULT_OK) {
                File cameraFile = new File(mCameraFilePath);
                if (cameraFile.exists()) {
                    result = Uri.fromFile(cameraFile);
                    // Broadcast to the media scanner that we have a new photo
                    // so it will be added into the gallery for the user.
                    //通知图库刷新一下新拍照的照片,但是实际并没有什么效果
                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
                }
            }
            //通知
            Intent it = new Intent();// 创建Intent对象
            it.setAction(FileChooserReceiver.Action);
            String path_ = UriUtil.getPath(getApplicationContext(), result);
            it.putExtra("fileFullName", path_ != null ? path_ : result.toString());
            sendBroadcast(it);
        }
    }

    /**
     * 显示自定义dialog 通过返回值来得到dialog.findViewById(R.id.buttonCallPhone);
     *
     * @param contentViewID
     * @param isCancelable
     * @return
     */
    public android.app.Dialog showSimpleCustomDialogMessage(int contentViewID, boolean isCancelable) {

        boolean isLightTheme = ThemeManager.getInstance().getCurrentTheme() == 0;
        Dialog.Builder builder = new SimpleDialog.Builder(isLightTheme ? R.style.SimpleDialogLight : R.style.SimpleDialog);
        builder.contentView(contentViewID);


        DialogFragment fragment = DialogFragment.newInstance(builder);
        fragment.setCancelable(isCancelable);
        fragment.show(getSupportFragmentManager(), null);
        //没有这句builder.getDialog();为空
        getSupportFragmentManager().executePendingTransactions();

        return builder.getDialog();
    }

    /**
     * 重写此方法以便监听网络状态的改变,必须先在Application中设置setIsNetworkStateReceiver(true),默认是设置true的
     *
     * @param context
     * @param intent
     * @param isWifi             是否是wifi连接 true wifi; false gprs
     * @param isNetworkAvailable 是否有网络  false 是没有
     */
    public void onNetworkStateChange(Context context, Intent intent, boolean isWifi, boolean isNetworkAvailable, String message) {
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (UIApplication.isNetworkStateReceiver() && androidNetConnectionChangeStateReceiver != null && netStateReceiver != null) {
            registerReceiver(androidNetConnectionChangeStateReceiver, new IntentFilter(androidNetConnectionChangeStateReceiver.Action));
            registerReceiver(netStateReceiver, new IntentFilter(netStateReceiver.Action));
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (UIApplication.isNetworkStateReceiver() && androidNetConnectionChangeStateReceiver != null && netStateReceiver != null) {
            unregisterReceiver(androidNetConnectionChangeStateReceiver);
            unregisterReceiver(netStateReceiver);
        }
    }
}
